<template>
  <el-collapse :model-value="['1', '2']">
    <div class="card-container">
      <el-collapse-item title="预期研究主要技术成果" name="1">
        <el-row :gutter="10" class="mb8" v-if="route.query.type !== 'look'">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
            >删除
            </el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="achievementsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <!--          <el-table-column label="id" align="center" prop="id"/>-->
          <el-table-column label="研究开始时间" align="center" prop="researchEndDate"/>
          <el-table-column label="研究结束时间" align="center" prop="researchStartDate"/>
          <el-table-column label="研究主要内容" align="center" prop="mainResearchContent"/>
          <el-table-column label="成果形式" align="center" prop="achievementForm"/>
          <el-table-column label="承担人" align="center" prop="responsiblePerson"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row, scope.$index)" v-if="route.query.type !== 'look'">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row, scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改预期研究的主要技术成果对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
          <el-form ref="achievementsRef" :model="form" :rules="rules" label-width="auto">
            <!--            <el-form-item label="研究开始时间" prop="researchEndDate">-->
            <!--              <el-input v-model="form.researchEndDate" placeholder="请输入研究开始时间"/>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="研究结束时间" prop="researchStartDate">-->
            <!--              <el-input v-model="form.researchStartDate" placeholder="请输入研究结束时间"/>-->
            <!--            </el-form-item>-->
            <el-form-item label="研究时间区间" prop="time">
              <!--                <el-input v-model="form.time" placeholder="请输入项目负责人"/>-->
              <el-date-picker
                  v-model="form.time"
                  type="daterange"
                  range-separator="To"
                  start-placeholder="请选择研究开始时间"
                  end-placeholder="请选择研究结束时间"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="研究主要内容">
              <el-input v-model="form.mainResearchContent" placeholder="请输入研究主要内容"/>
            </el-form-item>
            <el-form-item label="成果形式" prop="achievementForm">
              <el-input v-model="form.achievementForm" placeholder="请输入成果形式"/>
            </el-form-item>
            <el-form-item label="承担人" prop="responsiblePerson">
              <el-input v-model="form.responsiblePerson" placeholder="请输入承担人"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-collapse-item>
    </div>
    <div class="card-container">
      <el-collapse-item title="最终成果" name="2">
        <el-row :gutter="10" class="mb8" v-if="route.query.type !== 'look'">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd2"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple2"
                @click="handleDelete2"
            >删除
            </el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading2" :data="achievementsList2" @selection-change="handleSelectionChange2">
          <el-table-column type="selection" width="55" align="center"/>
          <!--          <el-table-column label="id" align="center" prop="id"/>-->
          <el-table-column label="完成时间" align="center" prop="completionDate"/>
          <el-table-column label="最终成果名称" align="center" prop="finalAchievementName"/>
          <el-table-column label="成果形式" align="center" prop="achievementForm"/>
          <el-table-column label="预计字数" align="center" prop="estimatedWordCount"/>
          <el-table-column label="参加人" align="center" prop="participants"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate2(scope.row, scope.$index)" v-if="route.query.type !== 'look'">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete2(scope.row, scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total2>0"
            :total="total2"
            v-model:page="queryParams2.pageNum"
            v-model:limit="queryParams2.pageSize"
            @pagination="getList2"
        />
        <div style="display: flex; justify-content: flex-end; margin-top: 60px; margin-bottom: 10px;" v-if="route.query.type !== 'look'">
          <el-button type="primary" @click="onSubmit(0)">保存草稿</el-button>
          <el-button type="primary" @click="onSubmit(1)">下一步</el-button>
          <el-button>取消</el-button>
        </div>
        <!-- 添加或修改预期研究的主要技术成果对话框 -->
        <el-dialog :title="title2" v-model="open2" width="500px" append-to-body>
          <el-form ref="achievementsRef2" :model="form2" :rules="rules2" label-width="auto">
            <!--            <el-form-item label="研究开始时间" prop="researchEndDate">-->
            <!--              <el-input v-model="form2.researchEndDate" placeholder="请输入研究开始时间"/>-->
            <!--            </el-form-item>-->
            <el-form-item label="完成时间" prop="completionDate">
              <!--              <el-input v-model="form2.completionDate" placeholder="请输入研究结束时间"/>-->
              <el-date-picker
                  v-model="form2.completionDate"
                  type="date"
                  placeholder="请输入研究结束时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="最终成果名称" prop="finalAchievementName">
              <el-input v-model="form2.finalAchievementName" placeholder="请输入最终成果名称"/>
            </el-form-item>
            <el-form-item label="成果形式" prop="achievementForm">
              <el-input v-model="form2.achievementForm" placeholder="请输入成果形式"/>
            </el-form-item>
            <el-form-item label="预计字数" prop="estimatedWordCount">
              <el-input-number v-model="form2.estimatedWordCount" controls-position="right" placeholder="请输入承担人" style="width: 100%"/>
            </el-form-item>
            <el-form-item label="参加人" prop="participants">
              <el-input v-model="form2.participants" placeholder="请输入承担人"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm2">确 定</el-button>
              <el-button @click="cancel2">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-collapse-item>
    </div>
  </el-collapse>
</template>

<script setup>
// import {listAchievements, getAchievements, delAchievements, addAchievements, updateAchievements} from "@/api/departmentWaterResources/achievements";
import {getKeyAchievements, getFinalAchievements, achievementsAddOrUpdate, addOrUpdateProjectOverview} from "@/api/departmentWaterResources/project.js";
import {useRoute} from "vue-router";
import {parseTime} from "@/utils/ruoyi.js";

const {proxy} = getCurrentInstance();
const route = useRoute();
// 表单1
const achievementsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const tableSelectIndex = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

/** 查询预期研究的主要技术成果列表 */
function getList() {
  loading.value = true;
  getKeyAchievements({...queryParams.value, projectId: route.query.id}).then(response => {
    achievementsList.value = response.rows;
    achievementsList.value.forEach((item) => {
      item.time = [item.researchEndDate, item.researchStartDate]
    })
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm("achievementsRef");
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加预期研究的主要技术成果";
}

/** 修改按钮操作 */
function handleUpdate(row, index) {
  // reset();
  // const _id = row.id || ids.value
  // getAchievements(_id).then(response => {
  tableSelectIndex.value = index;
  form.value = {...row};
  open.value = true;
  title.value = "修改预期研究的主要技术成果";
  // });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["achievementsRef"].validate(valid => {
    if (valid) {
      let data = {...form.value}
      data.researchEndDate = data.time[0]
      data.researchStartDate = data.time[1]
      if (title.value === "修改预期研究的主要技术成果") {
        // let index = achievementsList.value.findIndex(item => item.idcard === form.value.idcard)
        achievementsList.value[tableSelectIndex.value] = data
        open.value = false;
      } else {
        // addAchievements(form.value).then(response => {
        //   proxy.$modal.msgSuccess("新增成功");
        //   open.value = false;
        //   getList();
        // });
        achievementsList.value.push(data)
        open.value = false;
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row, index) {
  tableSelectIndex.value = index;
  // const _ids = row.id || ids.value;
  // proxy.$modal.confirm('是否确认删除预期研究的主要技术成果编号为"' + _ids + '"的数据项？').then(function () {
  //   return delAchievements(_ids);
  // }).then(() => {
  //   getList();
  //   proxy.$modal.msgSuccess("删除成功");
  // }).catch(() => {
  // });
  console.log(tableSelectIndex.value, achievementsList.value)
  if (multiple.value) {
    achievementsList.value.splice(tableSelectIndex.value, 1)
  } else {

  }
}

getList();

// 表单2
const achievementsList2 = ref([]);
const open2 = ref(false);
const loading2 = ref(true);
const showSearch2 = ref(true);
const ids2 = ref([]);
const single2 = ref(true);
const multiple2 = ref(true);
const total2 = ref(0);
const title2 = ref("");

const data2 = reactive({
  form2: {},
  queryParams2: {
    pageNum: 1,
    pageSize: 10,
  },
  rules2: {}
});

const {queryParams2, form2, rules2} = toRefs(data2);

/** 查询预期研究的主要技术成果列表 */
function getList2() {
  loading2.value = true;
  getFinalAchievements({...queryParams.value, projectId: route.query.id}).then(response => {
    achievementsList2.value = response.rows;
    total2.value = response.total;
    loading2.value = false;
  });
}

// 取消按钮
function cancel2() {
  open2.value = false;
  reset();
}

// 表单重置
function reset2() {
  form2.value = {};
  proxy.resetForm("achievementsRef");
}

// 多选框选中数据
function handleSelectionChange2(selection) {
  ids2.value = selection.map(item => item.id);
  single2.value = selection.length != 1;
  multiple2.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd2() {
  reset2();
  open2.value = true;
  title2.value = "添加项目最终成果";
}

/** 修改按钮操作 */
function handleUpdate2(row, index) {
  // reset2();
  // const _id = row.id || ids2.value
  // getAchievements(_id).then(response => {
  tableSelectIndex.value = index;
  form2.value = {...row};
  open2.value = true;
  title2.value = "修改项目最终成果";
  // });
}

/** 提交按钮 */
function submitForm2() {
  proxy.$refs["achievementsRef2"].validate(valid => {
    if (valid) {
      if (title2.value === "修改项目最终成果") {
        // updateAchievements2(form2.value).then(response => {
        //   proxy.$modal.msgSuccess("修改成功");
        //   open2.value = false;
        //   getList2();
        // });
        achievementsList2.value[tableSelectIndex.value] = form2.value
        open2.value = false
      } else {
        // addAchievements2(form2.value).then(response => {
        //   proxy.$modal.msgSuccess("新增成功");
        //   open2.value = false;
        //   getList2();
        // });
        achievementsList2.value.push(form2.value)
        open2.value = false;
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete2(row, index) {
  tableSelectIndex.value = index;
  // const _ids = row.id || ids2.value;
  // proxy.$modal.confirm('是否确认删除预期研究的主要技术成果编号为"' + _ids + '"的数据项？').then(function () {
  //   return delAchievements(_ids);
  // }).then(() => {
  //   getList2();
  //   proxy.$modal.msgSuccess("删除成功");
  // }).catch(() => {
  // });
  if (multiple2.value) {
    achievementsList2.value.splice(tableSelectIndex.value, 1)
  } else {

  }
}

const onSubmit = (type) => {
  achievementsAddOrUpdate({keyTechnicalAchievementsList: achievementsList.value, finalAchievementsList: achievementsList2.value, projectId: route.query.id}).then(response => {
    if (type === 0) {
      proxy.$modal.msgSuccess("保存成功");
    } else {
      emit('activeNext', 'tab7')
    }
  });
}

getList2();
</script>

<style scoped lang="scss">
.card-container :deep(.el-collapse-item__content) {
  padding: 0;
}

.tips {
  color: red;
  margin: 20px;
}
</style>
